package com.myutils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

/**
 * 额外的功能函数
 * 
 * @author Lan
 * @date 2012-7-26
 */
public class Function {

	protected static Logger logger = Logger.getLogger(Function.class);

	/**
	 * 转码[GBK -> ISO-8859-1]
	 * 
	 * @author Lan
	 * @param str
	 * @return
	 */
	public static String gbkToiso8859(String str) {
		String result = "";
		try {
			if (StringUtils.isNotBlank(str)) {
				result = new String(str.getBytes("GBK"), "iso-8859-1");
			}
		} catch (UnsupportedEncodingException e) {
			logger.error("转码出错", e);
		}
		return result;
	}

	/**
	 * 获取当前操作系统的后缀
	 * 
	 * @author Lan
	 * @return linux/windows
	 */
	public static String getSystemSuffix() {
		String suffix = "";
		if (isLinuxOS()) {
			// 若为linux系统
			suffix = "linux";
		} else {
			// windows 系统
			suffix = "windows";
		}
		return suffix;
	}

	/**
	 * 判断当前的操作系统是否为Linux
	 * 
	 * @author Lan
	 * @return true-Linux,false-Windows
	 */
	public static boolean isLinuxOS() {
		boolean flag = false;
		String osName = System.getProperty("os.name");

		if (StringUtils.indexOf(osName, "Windows") != -1) {
			flag = false;
		} else {
			flag = true;
		}
		return flag;
	}

	/**
	 * 获取classes目录的绝对路径
	 * 
	 * @return
	 */
	public static String getAbsolutePath(Class<?> inputClass) {
		String path = null;
		try {
			path = URLDecoder.decode(inputClass.getResource("/").getPath(),
					"utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return path;
	}

	/**
	 * 全角转换成半角
	 * @author Lan
	 * @param fullWidthStr 带有全角字符的字符串
	 * @return
	 */
	public static final String fullToHalfWidth(String fullWidthStr) {
		char[] chr = fullWidthStr.toCharArray();
		String str = "";
		for (int i = 0; i < chr.length; i++) {
			if ((int) chr[i] < 65248) {
				chr[i] = chr[i];
			} else
				chr[i] = (char) ((int) chr[i] - 65248);

			str += chr[i];
		}
		return str;
	}
	
	/**
	 * 冒泡排序：从小到大
	 * @author Lan
	 * @param a
	 */
	public static void bubbleSort(Integer[] a) {
		int temp = 0;
		for (int i = 0; i < a.length - 1; i++) {
			for (int j = 0; j < a.length - 1 - i; j++) {
				if (a[j] > a[j + 1]) {
					temp = a[j];
					a[j] = a[j + 1];
					a[j + 1] = temp;
				}
			}
		}
	}
	
	/**
	 * 在字符串的左边补0
	 * @param strInput 需补0的字符串
	 * @param length 返回字符串长度
	 * @return
	 */
	public static String addLeftZero(String strInput, int length) {
		if (StringUtils.isBlank(strInput) || length <= 0) {
			return strInput;
		}
		
		int cnt = length - strInput.length();
		if (cnt <= 0) {
			return strInput;
		}
		
		String zeroStrs = "";
		for (int i = 0; i < cnt; i++) {
			zeroStrs = zeroStrs + "0";
		}
		
		return zeroStrs + strInput;
	}
}
